//
//  YGRegisterViewController.m
//  yuanshangyiliao
//
//  Created by icholab on 2021/3/16.
//

#import "YGRegisterViewController.h"
#import "YGRegisterPhoneTableViewCell.h"
#import "YGCodeTableViewCell.h"
#import "YGSelectViewTableViewCell.h"
#import <YYText/YYText.h>
#import "YGRegisterBLL.h"
#import "YGRegisterConfigureModel.h"
#import "YGUserInfoModel.h"
#import "YGUserTypeModel.h"
#import "YGSickTypeModel.h"
#import "TTDatePickView.h"
#import "YGTimeTableViewCell.h"
#import "YGWebViewViewController.h"
#import "YGRecommandModel.h"
#import "YGRootView.h"
@interface YGRegisterViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *registerBtn;
@property (nonatomic, strong) NSArray  *userTypeArray;
@property (nonatomic, strong) YGRegisterConfigureModel  *infoModel;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) TTDatePickView  *brithPickView;//
@property (nonatomic, strong) NSString  *serverContent;
@property (nonatomic, strong) NSString  *slaContent;
@property (nonatomic, assign) BOOL  isSelect;

@end

@implementation YGRegisterViewController

static NSInteger AllRow = 116;
#pragma mark - lift cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"注册";
   
    [self initView];
    
    [self initContaints];
    
    [self requestData];
    
    [self reloadData];
    // Do any additional setup after loading the view.
}

#pragma mark - private
- (void)initView{
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.contentView];
    [self.contentView addSubview:self.bottomView];
    NSInteger row = AllRow; //16行
    WeakSelf(self);
    for (int i = 100; i < row; i++) {
        if (i == 100) {
            YGRegisterPhoneTableViewCell *cell = [[YGRegisterPhoneTableViewCell alloc] initWithFrame:CGRectZero];
            [cell setTitle:@"手机号:"];
            cell.tag = i;
            [self.contentView addSubview:cell];
            cell.CallBack = ^(id  _Nonnull data, NSInteger tag) {
                weakself.infoModel.phone = data;
            };
        }else if (i >= (101) && i <= 108 ){
            YGCodeTableViewCell *cell = [[YGCodeTableViewCell alloc] initWithFrame:CGRectZero];
            NSDictionary *dic = [[self data] objectAtIndex:i - 101];
            NSString *title = [dic objectForKey:@"title"];
            NSString *plachodler = [dic objectForKey:@"placholer"];
            cell.tag = i;
            [cell setTitle:title];
            [cell setPlaceHolder:plachodler];
            if(i>=106 && i<= 108){
                [cell unInput];
            }
            cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                if (i == 101) {
                    weakself.infoModel.code = data;
                }else if (i == 102){
                    weakself.infoModel.pwd = data;
                }else if (i == 103){
                    weakself.infoModel.sure_pwd = data;
                }else if (i == 104){
                    weakself.infoModel.name = data;
                }else if (i == 105){
                    weakself.infoModel.recommand_dr = data;
                    [weakself requestRecommandWithCode:data];
                    //医生推荐码
                }else if (i == 106){
                    weakself.infoModel.hospital = data;
                }else if (i == 107){
                    weakself.infoModel.department = data;
                }else if (i == 108){
                    weakself.infoModel.attending_dr = data;
                }
            };
            [self.contentView addSubview:cell];
        }else if (i == 109){
            YGSelectViewTableViewCell *cell = [[YGSelectViewTableViewCell alloc] initWithFrame:CGRectZero];
            cell.tag = i;
            [cell setTitle:@"患者属性:"];
            [cell setDefaultContent:@"请选择属性"];
            cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                if (tag == - 100) {
                    //无数据，重新请求
                    [weakself requestUserTypes];;
                    return;
                }
                YGUserTypeModel *model = [weakself.infoModel.userTypes objectAtIndex:tag];
                weakself.infoModel.user_type = model;
            };
            cell.showCallBack = ^(BOOL show, NSInteger tag) {
               
                [weakself setuserInteractionEnabledWithTag:tag enabled:!show];
            };
            [self.contentView addSubview:cell];
        }else if (i == 110){
            YGSelectViewTableViewCell *cell = [[YGSelectViewTableViewCell alloc] initWithFrame:CGRectZero];
            cell.tag = i;
            [cell setTitle:@"性别:"];
            [cell setDefaultContent:@"请选择性别"];
            cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                NSString *sex = [weakself.infoModel.sexs objectAtIndex:tag];
                weakself.infoModel.sex = sex;
            };
            cell.showCallBack = ^(BOOL show, NSInteger tag) {
                [weakself setuserInteractionEnabledWithTag:tag enabled:!show];
            };
            [self.contentView addSubview:cell];
        }else if (i == 111){
            YGCodeTableViewCell *cell = [[YGCodeTableViewCell alloc] initWithFrame:CGRectZero];
            cell.tag = i;
            [cell setTitle:@"年龄"];
            [cell setPlaceHolder:@"请输入年龄"];
            cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                weakself.infoModel.age = data;
            };
            [self.contentView addSubview:cell];
        }else if (i == 112){
            YGCodeTableViewCell *cell = [[YGCodeTableViewCell alloc] initWithFrame:CGRectZero];
            cell.tag = i;
            [cell setTitle:@"床位"];
            [cell setPlaceHolder:@"请输入床位"];
            cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                weakself.infoModel.bedid = data;
            };
            [self.contentView addSubview:cell];
        }else{
            //113 - 115
            NSDictionary *dic = [[self selectData] objectAtIndex:i - 113];
            NSString *title = [dic objectForKey:@"title"];
            NSString *plachodler = [dic objectForKey:@"placholer"];
            if (i == 113) {
                //
                YGTimeTableViewCell *cell = [[YGTimeTableViewCell alloc] initWithFrame:CGRectZero];
                cell.tag = i;
                [cell setTitle:title];
                [cell setPlaceHolder:plachodler];
                cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                    [weakself.brithPickView show];
                };
                [self.contentView addSubview:cell];
            }else{
               
                YGSelectViewTableViewCell *cell = [[YGSelectViewTableViewCell alloc] initWithFrame:CGRectZero];
            
                cell.tag = i;
                [cell setTitle:title];
                [cell setDefaultContent:plachodler];
                __weak YGSelectViewTableViewCell *cell1 = cell;
                cell.CallBack = ^(id  _Nonnull data,NSInteger tag) {
                    if (cell1.tag == 114) {
                        if (tag == - 100) {
                            //无数据，重新请求
                            [weakself requestSick];
                            return;
                        }
                        YGSickTypeModel *model = [weakself.infoModel.sickTypes objectAtIndex:tag];
                        weakself.infoModel.sickType = model;
                    }else{
                        
                        weakself.infoModel.lose_weight = [weakself.infoModel.lose_weights objectAtIndex:tag];
                    }
                };
                cell.showCallBack = ^(BOOL show, NSInteger tag) {
                    
                    [weakself setuserInteractionEnabledWithTag:tag enabled:!show];
                };
                [self.contentView addSubview:cell];
            }
            
        }
    }
}

- (void)initContaints{
   
 
    UIView *lastView;
    for (int i = 100; i < 100 + AllRow; i++) {
       UIView *view = [self.contentView viewWithTag:i];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@40);
            make.width.mas_equalTo(self.view.width);
            if (lastView) {
                make.top.mas_equalTo(lastView.mas_bottom);
            }
        }];
        lastView = view;
    }
    
    self.bottomView.top = 40 * 16;
    [self.scrollView setContentSize:CGSizeMake(self.view.width, self.bottomView.bottom)];
}

- (void)requestData{
    WeakSelf(self);
    [self requestUserTypes];
    [self requestSick];
    [YGRegisterBLL requestServersuccess:^(NSString * _Nonnull content) {
        weakself.serverContent = content;
    }];
    [YGRegisterBLL requestSLAsuccess:^(NSString * _Nonnull content) {
        weakself.slaContent = content;
    }];
}

- (void)requestUserTypes{
    WeakSelf(self);
    [YGRegisterBLL requestRigisterNumberTypeWithSuccess:^(NSArray<YGUserTypeModel *> * _Nonnull model) {
        weakself.infoModel.userTypes = model;
        [weakself reloadData];
    } fail:^(NSError * _Nonnull error) {

    }];

}

- (void)requestSick{
    WeakSelf(self);
    [YGRegisterBLL requestRigisterSickTypeWithSuccess:^(NSArray<YGSickTypeModel *> * _Nonnull model) {
        weakself.infoModel.sickTypes = model;
        [weakself reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];
    
}
- (void)requestRegisterAction{
    [YGRegisterBLL rquestRegisterModel:self.infoModel success:^() {
        //注册成g
        [YGRootView resetRootViewController];
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestRecommandWithCode:(NSString *)code{
    WeakSelf(self);
    [YGRegisterBLL requestRecommandCode:code success:^(YGRecommandModel * _Nonnull model) {
        weakself.infoModel.department = model.departmentName;
        weakself.infoModel.hospital = model.hospitalsName;
        weakself.infoModel.attending_dr = model.name;
        weakself.infoModel.recommandModel = model;
        [weakself reloadData];
    } fail:^(NSError * _Nonnull error) {
        
    }];

}
- (void)reloadData{
    for (int i = 100; i < AllRow; i++) {
        YGRegisterTableViewCell *view = [self.contentView viewWithTag:i];
        [view configureData:self.infoModel];
    }
}

- (void)setuserInteractionEnabledWithTag:(NSInteger)tag enabled:(BOOL)enabled{
    for (NSInteger i = tag + 1; i < AllRow; i ++) {
        YGRegisterTableViewCell *view = [self.contentView viewWithTag:i];
        view.userInteractionEnabled = enabled;
    }
}

- (void)clickSelectAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    self.isSelect = sender.selected;
}

- (void)clickRegisterAction{    
    if ([self isEmpty:self.infoModel.phone]) {
        [self showStatusWithAutoHiden:@"请输入手机号"];
    }else if ([self isEmpty:self.infoModel.code]) {
        [self showStatusWithAutoHiden:@"请输入验证码"];
    }else if ([self isEmpty:self.infoModel.pwd]) {
        [self showStatusWithAutoHiden:@"请输入密码"];
    }else if ([self isEmpty:self.infoModel.sure_pwd]) {
        [self showStatusWithAutoHiden:@"请输入确认密码"];
    }else if ([self isEmpty:self.infoModel.name]) {
        [self showStatusWithAutoHiden:@"请输入真实姓名"];
    }else if ([self isEmpty:self.infoModel.recommand_dr]) {
        [self showStatusWithAutoHiden:@"请输入推荐码"];
    }else if (!self.infoModel.user_type) {
        [self showStatusWithAutoHiden:@"请输入患者属性"];
    }else if ([self isEmpty:self.infoModel.age]) {
        [self showStatusWithAutoHiden:@"请输入年龄"];
    }else if ([self isEmpty:self.infoModel.bedid]) {
        [self showStatusWithAutoHiden:@"请输入床位"];
    }else if ([self isEmpty:self.infoModel.time]) {
        [self showStatusWithAutoHiden:@"请输入入院时间"];
    }else if (!self.infoModel.sickType) {
        [self showStatusWithAutoHiden:@"请输入疾病类型"];
    }else if ([self isEmpty:self.infoModel.lose_weight]) {
        [self showStatusWithAutoHiden:@"请选择是否减重"];
    }else if (!self.isSelect){
        [self showStatusWithAutoHiden:@"请勾选登录即代表同意"];
    }else{
        [self requestRegisterAction];
    }
}

- (BOOL)isEmpty:(NSString *)str{
    if (str.length ==0 || str == nil) {
        return YES;
    }
    return NO;
}
#pragma mark - dateDatate
- (void)ttDatePickEnsureAction:(NSString *)YMd date:(NSDate *)date {
//    [self updateUserInfo:@"birth" value:YMd];
    self.infoModel.time = YMd;
    NSInteger hospitalTime = [date timeIntervalSince1970]*1000;
    self.infoModel.hospitalTime = [NSNumber numberWithInteger:hospitalTime];
    [self reloadData];
}

#pragma mark - setter

- (UIView *)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:self.scrollView.bounds];
    }
    return _contentView;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 120)];
        UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 20, 20)];
        [selectBtn addTarget:self action:@selector(clickSelectAction:) forControlEvents:UIControlEventTouchUpInside];
        selectBtn.layer.borderWidth = 0.5;
        selectBtn.clipsToBounds = YES;
        [selectBtn setImage:[UIImage imageNamed:@"register_select"] forState:UIControlStateSelected];
        [_bottomView addSubview:selectBtn];
        
        YYLabel *ruleLabel = [[YYLabel alloc] initWithFrame:CGRectMake(selectBtn.right + 5, 0, 280, 20)];
        ruleLabel.font = [UIFont systemFontOfSize:12];
        ruleLabel.userInteractionEnabled = YES;
        ruleLabel.centerY = selectBtn.centerY;
        ruleLabel.attributedText = [self getProtocolContent];
        [_bottomView addSubview:ruleLabel];
        
        [_bottomView addSubview:self.registerBtn];
        self.registerBtn.frame = CGRectMake(selectBtn.left , selectBtn.bottom + 10, _bottomView.width - 20, 50);
        
        YYLabel *backLogin = [[YYLabel alloc] initWithFrame:CGRectMake(0, self.registerBtn.bottom + 10, 100, 20)];
        self.registerBtn.layer.cornerRadius = 8;
        self.registerBtn.clipsToBounds = YES;
        backLogin.centerX = self.view.centerX;
        backLogin.textAlignment = NSTextAlignmentCenter;
        backLogin.userInteractionEnabled = YES;
        backLogin.attributedText = [self getBackLoginContent];
        [_bottomView addSubview:backLogin];
        
    }
    return _bottomView;
}

- (UIButton *)registerBtn{
    if (!_registerBtn) {
        _registerBtn = [[UIButton alloc] initWithFrame:CGRectZero];
        _registerBtn.backgroundColor = UIColorFromRGB(0x37C8D7);
        [_registerBtn addTarget:self action:@selector(clickRegisterAction) forControlEvents:UIControlEventTouchUpInside];
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    return _registerBtn;
}

- (YGRegisterConfigureModel *)infoModel{
    if (!_infoModel) {
        _infoModel = [[YGRegisterConfigureModel alloc] init];
    }
    return _infoModel;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
//        _scr
    }
    return _scrollView;
}

- (TTDatePickView *)brithPickView {
    if (!_brithPickView) {
        UIView *view = [UIApplication sharedApplication].keyWindow;
        _brithPickView = [[TTDatePickView alloc] initWithFrame:view.bounds];
        _brithPickView.limitAge = 0;
        _brithPickView.delegate = self;
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        
        NSDate *endDate = [formatter dateFromString:@"1945-01-01"];
        
        _brithPickView.minimumDate = endDate;
        _brithPickView.maximumDate = [NSDate date];
        [view addSubview:_brithPickView];
    }
    return _brithPickView;
}

- (NSMutableAttributedString *)getProtocolContent{
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"登录即代表同意 "];
    attString.yy_color = UIColorFromRGB(0x333333);
    
    NSString *protocolString = @"源高服务协议";
    
    NSMutableAttributedString *privateString = [[NSMutableAttributedString alloc] initWithString:protocolString attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x37C8D7)}];
    WeakSelf(self);
    [privateString yy_setTextHighlightRange:NSMakeRange(0, privateString.length) color:nil backgroundColor:nil userInfo:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
//        StrongSelf(self);
        YGWebViewViewController *vc = [[YGWebViewViewController alloc] init];
        vc.title = protocolString;
        
        [vc loadContent:weakself.slaContent];
        [weakself.navigationController pushViewController:vc animated:YES];
//        @strongify(self);
        // 跳转隐私政策
//        [self goToWebview:HtmlUrlKey(kPrivacyURL)];
    } longPressAction:nil];
    
    NSString *userString = @"隐私政策";
    NSMutableAttributedString *userAttString = [[NSMutableAttributedString alloc] initWithString:userString attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x37C8D7)}];
    [userAttString yy_setTextHighlightRange:NSMakeRange(0, userAttString.length) color:nil backgroundColor:nil userInfo:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {

        YGWebViewViewController *vc = [[YGWebViewViewController alloc] init];
        vc.title = userString;
        
        [vc loadContent:weakself.slaContent];
        [weakself.navigationController pushViewController:vc animated:YES];
    } longPressAction:nil];
    [attString appendAttributedString:privateString];
    [attString appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" 与 "]];
    [attString appendAttributedString:userAttString];
    
    return attString;
}

- (NSMutableAttributedString *)getBackLoginContent{
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"已注册过 "];
    attString.yy_color = UIColorFromRGB(0x999999);
    
    NSString *protocolString = @"登录";
    
    NSMutableAttributedString *privateString = [[NSMutableAttributedString alloc] initWithString:protocolString attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x37C8D7)}];
    WeakSelf(self);
    [privateString yy_setTextHighlightRange:NSMakeRange(0, privateString.length) color:nil backgroundColor:nil userInfo:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakself.navigationController popViewControllerAnimated:YES];
    } longPressAction:nil];
    
    [attString appendAttributedString:privateString];

    return attString;
}

- (NSArray *)data{
    NSArray *data = @[
    @{@"title":@"验证码",@"placholer":@"请输入验证码"},
    @{@"title":@"密码",@"placholer":@"6-16位字母、数字或符号组合"},
    @{@"title":@"确认密码",@"placholer":@"6-16位字母、数字或符号组合"},
    @{@"title":@"真实姓名",@"placholer":@"请输入真实姓名"},
    @{@"title":@"医生推荐码",@"placholer":@"请输入推荐码"},
    @{@"title":@"所在医院",@"placholer":@""},
    @{@"title":@"科室",@"placholer":@""},
    @{@"title":@"我的主诊医生",@"placholer":@""},
    ];
    return data;
}

- (NSArray *)selectData{
    NSArray *data = @[
    @{@"title":@"入院时间",@"placholer":@"请输入入院时间"},
    @{@"title":@"疾病类型",@"placholer":@"请选择疾病类型"},
    @{@"title":@"是否减重",@"placholer":@"请选择是否减重"},
    ];
    return data;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
